package com.alarm.ecp;

import com.alarm.ecp.constant.EventConstant;
import com.alarm.ecp.pojo.EventPO;
import com.alarm.ecp.utils.KafkaUtil;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.io.IOException;

/**
 * 检测最近1分钟内【连续】登录失败超过3次的用户
 * 基于【组合模式】
 * 组合模式.next(...)严格紧邻（连续事件）
 */
public class LoginFailByComposite {
    public static void main(String[] args) throws IOException {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        // kafka数据源
        DataStream<EventPO> eventStream = KafkaUtil.read(args, env);
        // 生成KeyedStream
        eventStream.keyBy(new KeySelector<EventPO, Integer>() {
            @Override
            public Integer getKey(EventPO eventPO) throws Exception {
                return eventPO.getUserId();
            }
        });
        Pattern<EventPO, EventPO> pattern = Pattern.<EventPO>begin("login_fail_first")
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        return EventConstant.LOGIN_FAIL.equals(eventPO.getEventName());
                    }
                })
                .next("login_fail_second") // 严格紧邻（连续事件）
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        return EventConstant.LOGIN_FAIL.equals(eventPO.getEventName());
                    }
                }).next("login_fail_third")
                .where(new SimpleCondition<EventPO>() {
                    @Override
                    public boolean filter(EventPO eventPO) throws Exception {
                        return EventConstant.LOGIN_FAIL.equals(eventPO.getEventName());
                    }
                }).within(Time.seconds(60));
    }
}
